#!/bin/bash
# 根据端口号，查找其对应进程，然后再递归查找其父进程，直到pid==1

# ss -H 不显示表头
pids=$(sudo ss -tunapH  | awk '{print $7}' | sed -E 's/.*pid=([0-9]+).*/\1/g' | sort -n | uniq )

#set -x


find_parent(){

	pid=$1
	count=$2 

	
	
	# ps -h 不显示表头
	process=$(ps -p $pid -h -o pid,ppid,cmd)
	
	parent_pid=$(echo $process | awk '{print $2}')

	cmd=$(echo $process | awk '{print $3}')
	str=""
	
	if [[ $pid -eq 1 ]]; then 
		# 已经抵达尽头	
		echo 0
		#sub_count=0
	
	else
	
		sub_count=$(find_parent $parent_pid  ${count+1} )
		
#		set -x	
		for (( i=0 ; i < sub_count ; i++)); do
			str+="\t"
		done
#		set +x

	fi

	str+=" $cmd"

	if [[ $count -eq 1 ]]; then
		port=$(sudo ss -tunlpH | grep "pid=$pid"| awk '{print $5}'| sed -E 's/.*:([0-9]+)$/\1/p' | sort |uniq | head -n 1)
		str+=" 监听 $port"
	fi

	printf "$str \n" >&2

	echo ${sub_count+1}
}


for pid in ${pids[@]}; do
	aa=$(find_parent $pid 1)
done
